package main

import (
	"fmt"
	"github.com/sirupsen/logrus"
	"github.com/spf13/viper"
	"google.golang.org/grpc"
	"net"
	"user/conf"
	"user/dao/mysql"
	"user/discovery"
	"user/handler"
	"user/model"
	pb "user/proto"
)

func main() {
	// 加载配置文件
	err := conf.InitConfig()
	if err != nil {
		fmt.Println("配置文件初始化失败!", err)
		return
	}

	fmt.Println("配置文件加载完毕!")

	// 初始化Redis连接池
	model.InitRedis()
	fmt.Println("redis数据库初始化完毕")

	// 初始化mysql连接
	err = mysql.Init()
	if err != nil {
		fmt.Println("mysql连接初始化失败:", err)
		return
	}
	fmt.Println("mysql连接初始化完毕。。。")

	// 微服务监听地址
	serverAddr := viper.GetString("server.grpcAddress")
	serviceName := viper.GetString("server.domain")
	etcdAddr := viper.GetString("etcd.address")

	etcdRegister := discovery.NewRegister([]string{etcdAddr}, logrus.New())
	defer etcdRegister.Stop()

	userNode := discovery.Server{
		Name: serviceName,
		Addr: serverAddr,
	}

	//初始化一个grpc对象
	grpcServer := grpc.NewServer()
	defer grpcServer.Stop()

	//2. 注册服务
	pb.RegisterUserServer(grpcServer, handler.New())

	//3. 设置监听
	listener, err := net.Listen("tcp", serverAddr)
	if err != nil {
		fmt.Println("Listen err:", err)
		return
	}
	defer listener.Close()
	//4. etcd中注册服务
	if _, err := etcdRegister.Register(userNode, 10); err != nil {
		panic(fmt.Sprintf("start server failed, err: %v", err))
	}
	logrus.Info("server started listen on ", serverAddr)

	//5. 启动服务
	grpcServer.Serve(listener)

}
